package com.suixun.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.suixun.controller.base.BaseController;
import com.suixun.domain.Operationer;
import com.suixun.service.OperationerService;
import com.suixun.utils.Constants;
import com.suixun.utils.MD5Util;

@RestController
@RequestMapping(("/operator"))
public class OperationerController extends BaseController {

	@Resource
	private OperationerService operationerService;

	/**
	 * 登录
	 * @param account
	 * @param password
	 * @param session
	 * @return
	 */
	@PostMapping(value = "/login")
	public Object login(String account, String password, HttpSession session) {
		if (StringUtils.isBlank(account)) {
			return fail("账号不能为空");
		}
		if (StringUtils.isBlank(password)) {
			return fail("密码不能为空");
		}
		Wrapper<Operationer> wrapper = new EntityWrapper<>();
		wrapper.eq("account", account);
		Operationer operationer = operationerService.selectOne(wrapper);
		if (operationer == null) {
			return fail("账号不存在");
		} else if (!operationer.getPassword().equals(MD5Util.doubleMD5(password))) {
			return fail("密码错误");
		}
		session.setAttribute(Constants.SESSION_OPERATIONER, operationer);
		return success();
	}

	/**
	 * 修改密码
	 * @param password
	 * @param session
	 * @return
	 */
	@PostMapping(value = "/updatePassword")
	public Object updatePassword(String password, HttpSession session) {
		if (StringUtils.isBlank(password)) {
			return fail("密码不能为空");
		}
		Operationer operationer = (Operationer) session.getAttribute(Constants.SESSION_OPERATIONER);
		operationer.setPassword(MD5Util.doubleMD5(password));
		operationerService.updateById(operationer);
		return success();
	}

	/**
	 * 退出登录
	 * @param session
	 * @return
	 */
	@PostMapping(value = "/logout")
	public Object logout(HttpSession session) {
		session.removeAttribute(Constants.SESSION_OPERATIONER);
		return success();
	}
}
